//
//  AppDelegate.swift
//  RouterPushProtocol
//
//  Created by Toj on 2/21/22.
//

/** Status bar
 1. Status bar is initially hidden 为 NO 时
 View controller-based status bar appearance 不生效
 2. View controller-based status bar appearance 为 NO 时
 preferredStatusBarStyle和prefersStatusBarHidden方法不生效
 3. UIViewController 在 UINavigationController 导航栏中时,
 在UIViewController中设置, preferredStatusBarStyle 不生效根本不会走
 因为 UINavigationController 中也有 preferredStatusBarStyle 这个方法, 会走UINavigationController.
 需要重写UINavigationController中的方法方能生效(可以通过分类的方式或者baseNavigationde 方式)
 */

// com.520it.www.iOS

import UIKit
import AdSupport
import AppTrackingTransparency

@_exported import TTCOM_iOS
@_exported import Toast

@main
class AppDelegate: UIResponder {
    
    var window: UIWindow?
    
    private func setupRootViewController() {
        print("-->toj: appDelegate machine: \(UIDevice.current.dv_machine)")
        
        window = UIWindow()
        window?.bounds = UIScreen.main.bounds
        window?.rootViewController = STTabBarController()
        window?.backgroundColor = UIColor.white
        // window?.rootViewController = ViewController()
        window?.makeKeyAndVisible()
    }
    
    private func setupMonitoring() {
        // FPS
        window?.addSubview(UIFPSLabel())
        // MTRunHawkeyeInOneLine.start()
        // 监控卡顿
        STBlockMonitor.share.start()
        // NSObject.addClassNames(toWhitelist:[NSStringFromClass(STAdsView.self)])
        
        // CrashHandler.setup {[weak self] (stackTrace, completion) in
        //      self?.showExceptionFor(Reason: stackTrace)
        //      completion()
        // }
    }
    
    func isApplicationActive(_ com: @escaping ((_ b: Bool) -> Void)) {
        var appState: UIApplication.State = .background
        if Thread.current.isMainThread {
            appState = UIApplication.shared.applicationState
            com(appState == .active)
        }
        
        print("-->startimes: appState1:\(appState.rawValue)")
        
        DispatchQueue.main.async {
            appState = UIApplication.shared.applicationState
            print("-->startimes: appState2:\(appState.rawValue)")
            com(appState == .active)
        }
        print("-->startimes: appState3:\(appState.rawValue)")
    }
    
    private func showExceptionFor(Reason reason:String,
                                  andTitle t:String = "app异常"){
        
        //var dismiss = false
        let currentRunloop = CFRunLoopGetCurrent()
        
        if let vc = UIApplication.shared.keyWindow?.rootViewController {
            let alertVC = UIAlertController(title: "错误", message: "原因", preferredStyle: .alert)
            
            alertVC.addTextField( configurationHandler: { text in
                text.text = reason
            })
            alertVC.addTextField( configurationHandler: { text in
                text.text = t
            })
            
            let action = UIAlertAction(title: "34", style: .cancel)
            alertVC.addAction(action)
            
            vc.present(alertVC, animated: true)
            
            if let arrModes = CFRunLoopCopyAllModes(currentRunloop) as? Array<CFString> {
                //while !dismiss {
                while true {
                    for model in arrModes {
                        CFRunLoopRunInMode(CFRunLoopMode.init(rawValue: model), 0.001, false)
                    }
                }
            }
        }
    }
}

extension AppDelegate: UIApplicationDelegate {
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        setupRootViewController()
        
        STLauncher.shared.setup(application: application, didFinishLaunchingWith: launchOptions)
        
#if DEBUG
        setupMonitoring()
#endif
        return true
    }
    
    // 唤醒app变的活跃, 就是从后台变到前台.
    // 1. app启动, 2. 后台回到前台
    func applicationDidBecomeActive(_ application: UIApplication) {
        // 追踪权限
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            AuthorizationManager.manager.at_requestTrackingAuthorization()
        }
    }
    
    // URL scheme 方式打开
    public func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        
        RouterManager.shared.push(url: url)
        
        return true
    }
    
    // 使用 Universal Links 通用连接 唤醒app
    func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
        
        return true
    }
    
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        // print("-->toj: class:\(st_className), func: \(#function)")
        return .allButUpsideDown
    }
}

//func STExceptionHandlers(exception: NSException) {
//    let name = exception.reason ?? ""
//    let message = exception.userInfo?.to_json ?? ""
//    UIAlertView(title: name, message: message, delegate: nil, cancelButtonTitle: "闪退").show()

// 本次异常处理， 保证弹框能正常弹出
//    let runloop = CFRunLoopGetCurrent()
//    let modes = CFRunLoopCopyAllModes(runloop) as NSArray
//    while true {
//        for mode in modes {
//            guard let m = mode as? CFRunLoopMode else { continue }
//            CFRunLoopRunInMode(m,  0.0001, false)
//        }
//    }
//}

//objc_setUncaughtExceptionHandler { res in
//    guard  let exc = res as? NSException else { return }
//    STExceptionHandlers(exception: exc)
//}
//
//NSSetUncaughtExceptionHandler { exc in
//    STExceptionHandlers(exception: exc)
//}

